#include "adjds371.h"
#include "i2c.h"

void adjds371_initialize(void) {
	i2c_initialize();
}

void adjds371_write_byte(unsigned char register_address, unsigned char register_value) {
	unsigned char dummy_byte = 0x00;

	// Write the I2C address wite write mode bit
	i2c_set_register(SENSOR_ADDRESS | DEVICE_WRITE);
	i2c_start();
	i2c_wait_tdre();

	// Write register address
	i2c_set_register(register_address);
	i2c_wait_tdre();
	dummy_byte = i2c_get_register();

	// Write the register value
	i2c_set_register(register_value);
	i2c_wait_tdre();
	i2c_stop();
}

unsigned char adjds371_read_byte(unsigned char register_address) {
	unsigned char dummy_byte = 0x00;
	unsigned char register_value = 0x00;

	// Write the I2C address with write mode bit
	i2c_set_register(SENSOR_ADDRESS | DEVICE_WRITE);
	i2c_start();
	i2c_wait_tdre();

	// Write the register address
	i2c_set_register(register_address);
	i2c_wait_tdre();
	dummy_byte = i2c_get_register();
	
	// Set the NAK bit
	i2c_no_ack();

	// Send the restart condition
	i2c_start();

	// Write the I2C address with read mode bit
	i2c_set_register(SENSOR_ADDRESS | DEVICE_READ);
	i2c_wait_tdre();
	i2c_wait_rdrf();
	register_value = i2c_get_register();
	i2c_stop();

	return register_value;
}